package com.wngbms.netty.book._06endec._01;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

public class StringReplayDecoder extends ReplayingDecoder<StringReplayDecoder.PHASE> {

    public enum PHASE {
        PHASE_1,
        PHASE_2,

    }

    int length;
    byte[] content;

    public StringReplayDecoder() {
        super(PHASE.PHASE_1);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        switch (state()) {
            case PHASE_1:
                length = in.readInt();
                content = new byte[length];
                checkpoint(PHASE.PHASE_2);
                break;
            case PHASE_2:
                in.readBytes(content, 0, length);
                out.add(new String(content));
                checkpoint(PHASE.PHASE_1);
                break;
            default:
        }
    }
}
